﻿using CNFM_CROCODILE_LOGO.RestClient.Domain;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace CNFM_CROCODILE_LOGO_Web.OAuthManagement
{
    public class PolicyHandler : AuthorizationHandler<PolicyRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
        {
            //赋值用户权限
            var userPermissions = requirement.UserPermissions;
            //从AuthorizationHandlerContext转成HttpContext，以便取出表求信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
            //请求Url
            var questUrl = httpContext.Request.Path.Value.ToUpperInvariant();

            //var isAuthenticateds = httpContext.User.Identity;
            //是否经过验证
            var isAuthenticated = httpContext.User.Identity.IsAuthenticated;

            //判断权限
            var auths = httpContext.AuthenticateAsync().Result.Principal.Claims;
            //  var Name = auths.FirstOrDefault(t => t.Type.Equals(ClaimTypes.Name))?.Value;

            var role = auths.FirstOrDefault(t => t.Type.Equals(ClaimTypes.Role))?.Value;
            var primarySid = auths.FirstOrDefault(t => t.Type.Equals(ClaimTypes.PrimarySid))?.Value;
            UserBasic.userId = primarySid;

            #region 权限到路由
            //if (isAuthenticated)
            //{
            //    if (userPermissions.GroupBy(g => g.Url).Any(w => w.Key.ToUpperInvariant() == questUrl))
            //    {
            //        //用户名
            //        var userName = httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.NameIdentifier).Value;
            //        if (userPermissions.Any(w => w.UserName == userName && w.Url.ToUpperInvariant() == questUrl))
            //        {
            //            context.Succeed(requirement);
            //        }
            //        else
            //        {
            //            //无权限跳转到拒绝页面
            //            httpContext.Response.Redirect(requirement.DeniedAction);
            //        }
            //    }
            //    else
            //    {
            //        context.Succeed(requirement);
            //    }
            //}
            #endregion

            if (!string.IsNullOrEmpty(role))
            {
                var userName = auths.FirstOrDefault(t => t.Type.Equals(ClaimTypes.Name))?.Value;
                var country = auths.FirstOrDefault(t => t.Type.Equals(ClaimTypes.Country))?.Value;
                //判断请求类型
                var method = httpContext.Request.Method;
                if (method == "GET" && role != "系统管理员" && role != "协会管理员" && role != "标识公司")
                    httpContext.Request.QueryString = httpContext.Request.QueryString.Add("areUnCode", country);
                if (method == "GET" && role == "企业用户")//questUrl == "/SIGNAGEAPPLICATION/GETIDENTIFICATIONALL"
                    httpContext.Request.QueryString = httpContext.Request.QueryString.Add("enterpriseId", auths.FirstOrDefault(t => t.Type.Equals(ClaimTypes.AuthenticationInstant))?.Value);

                UserPermission userPermission = new UserPermission()
                {
                    Url = questUrl,
                    UserName = userName
                };
                requirement.UserPermissions.Add(userPermission);

                context.Succeed(requirement);
                //if (userPermissions.Any(w => w.UserName == userName && w.Url.ToUpperInvariant() == questUrl))
                //{
                //    context.Succeed(requirement);
                //}
                //else
                //{
                //    //无权限跳转到拒绝页面
                //    httpContext.Response.Redirect(requirement.DeniedAction);
                //}
            }
            else
            {
                //无权限跳转到拒绝页面
                httpContext.Response.Redirect(requirement.DeniedAction);
            }
            return Task.CompletedTask;
        }
    }
}
